import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import eslintPlugin from 'vite-plugin-eslint'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
import { createHtmlPlugin } from 'vite-plugin-html'
// @see: https://vitejs.dev/config/
export default defineConfig((mode: ConfigEnv): UserConfig => {
	const env = loadEnv(mode.mode, process.cwd())
	const isBuild = mode.command === 'build'

	// @ts-ignore
	return {
		base: './',
		// alias config
		publicDir: '/public',
		resolve: {
			extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css'],
			alias: {
				'@': resolve(__dirname, './src'),
			},
		},
		// global css
		css: {
			//* css模块化
			modules: {
				// css模块化 文件以.module.[css|less|scss]结尾
				generateScopedName: '[name]__[local]___[hash:base64:5]',
				hashPrefix: 'prefix',
			},
			preprocessorOptions: {
				less: {
					javascriptEnabled: true,
					additionalData: '@import "./src/ui/antd/styles/common.less";',
				},
			},
		},
		// server config
		server: {
			host: '0.0.0.0', // 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
			port: Number(env.VITE_PORT),
			open: env.VITE_OPEN,
			cors: true,
			// https: false,
			// 代理跨域（mock 不需要配置，这里只是个事列）
			// proxy: {
			// 	'/api': {
			// 		target: 'https://mock.mengxuegu.com/mock/62abda3212c1416424630a45', // easymock
			// 		changeOrigin: true,
			// 		rewrite: path => path.replace(/^\/api/, '')
			// 	}
			// }
		},
		// plugins
		plugins: [
			react(),
			// 处理index.html模板
			createHtmlPlugin({
				inject: {
					data: {
						title: env.VITE_GLOB_APP_TITLE,
					},
				},
			}),
			// * 使用 svg 图标
			createSvgIconsPlugin({
				iconDirs: [resolve(process.cwd(), 'src/assets/icons')],
				symbolId: 'icon-[dir]-[name]',
			}),
			// * EsLint 报错信息显示在浏览器界面上
			eslintPlugin(),
			// * 是否生成包预览
			// @ts-ignore
			env.VITE_REPORT && visualizer(),
			viteMockServe({
				mockPath: 'mock',
				localEnabled: true,
				prodEnabled: true,
				//cors: true,
				logger: true,
				watchFiles: true,
			}),
		],
		esbuild: {
			pure: env.VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
		},
		// build configure
		build: {
			outDir: 'dist',
			// esbuild 打包更快，但是不能去除 console.log，去除 console 使用 terser 模式
			//minify: 'esbuild',
			// minify: "terser",
			// terserOptions: {
			// 	compress: {
			// 		drop_console: viteEnv.VITE_DROP_CONSOLE,
			// 		drop_debugger: true
			// 	}
			// },
			rollupOptions: {
				output: {
					// Static resource classification and packaging
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
				},
			},
		},
	}
})
